package com.feishi.core.socket.common.decoder;

import com.feishi.core.analytic.assembler.BaseAssembler;
import com.feishi.core.analytic.assembler.DefaultAssembler;
import com.feishi.core.socket.common.SocketDecoder;
import com.feishi.core.util.common.ByteUtil;
import com.feishi.core.util.common.bean.ByteBufferProxy;

import java.io.ByteArrayOutputStream;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-3-30 10:37
 **/
public class SplitDecoder<T extends BaseAssembler> implements SocketDecoder<T> {
    private  boolean escape;
    private char escapeCode;
    private char separatorCode;
    private Class<T> assemblerClass= (Class<T>) DefaultAssembler.class;

    public SplitDecoder(char separatorCode) {
        this.separatorCode = separatorCode;
        this.escape=false;
    }

    public SplitDecoder( char separatorCode,char escapeCode) {
        this.escapeCode = escapeCode;
        this.separatorCode = separatorCode;
        this.escape=true;
    }

    @Override
    public byte[] decode(ByteBufferProxy bfp) {
        int endIndex=getEndIndex(bfp.get());
        if(endIndex>=0){
            byte[] bs= bfp.get(endIndex);
            bfp.copyToStart(endIndex+1);
            return ByteUtil.removeEscapeCode(bs,this.escapeCode);
        }
        return null;
    }

    public void setAssemblerClass(Class<T> assemblerClass) {
        this.assemblerClass = assemblerClass;
    }

    @Override
    public Class getAssemblerClass() {
        return assemblerClass;
    }

    public int getEndIndex(byte[] bytes) {
        for (int i = 0; i < bytes.length; i++) {
            if(this.escape&&bytes[i]==escapeCode){
                i++;
                continue;
            }
            if(bytes[i]==separatorCode){
                return i;
            }
        }
        return -1;
    }


}
